import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../../../../core/controllers/base_controller.dart';

class MainTabController extends GetxController {
  // 当前选中的tab索引
  final _currentIndex = 0.obs;
  int get currentIndex => _currentIndex.value;
  
  // tab页面列表
  final List<Widget> pages = [];
  
  // tab配置
  final List<BottomNavigationBarItem> tabs = [
    const BottomNavigationBarItem(
      icon: Icon(Icons.home),
      activeIcon: Icon(Icons.home),
      label: '首页',
    ),
    const BottomNavigationBarItem(
      icon: Icon(Icons.list),
      activeIcon: Icon(Icons.list),
      label: '列表',
    ),
    const BottomNavigationBarItem(
      icon: Icon(Icons.person),
      activeIcon: Icon(Icons.person),
      label: '我的',
    ),
    const BottomNavigationBarItem(
      icon: Icon(Icons.settings),
      activeIcon: Icon(Icons.settings),
      label: '设置',
    ),
  ];
  
  @override
  void onInit() {
    super.onInit();
  }
  
  // 切换tab
  void changeTab(int index) {
    if (index != _currentIndex.value) {
      _currentIndex.value = index;
      update();
    }
  }
  
  // 获取当前页面标题
  String getCurrentTitle() {
    switch (_currentIndex.value) {
      case 0:
        return '首页';
      case 1:
        return '列表';
      case 2:
        return '我的';
      case 3:
        return '设置';
      default:
        return '主页面';
    }
  }
  
  // 双击退出相关
  DateTime? _lastPressedAt;
  
  // 处理返回按钮
  Future<bool> onWillPop() async {
    // 如果不在首页，先切换到首页
    if (_currentIndex.value != 0) {
      changeTab(0);
      return false;
    }
    
    // 在首页时处理双击退出
    final now = DateTime.now();
    if (_lastPressedAt == null || 
        now.difference(_lastPressedAt!) > const Duration(seconds: 2)) {
      _lastPressedAt = now;
      Get.snackbar('提示', '再按一次退出应用');
      return false;
    }
    
    return true;
  }
  
  // 跳转到指定tab
  void navigateToTab(int index) {
    if (index >= 0 && index < tabs.length) {
      changeTab(index);
    }
  }
  
  // 添加角标数字
  final _badgeCounts = <int, int>{}.obs;
  Map<int, int> get badgeCounts => _badgeCounts;
  
  // 设置角标数字
  void setBadgeCount(int tabIndex, int count) {
    if (count > 0) {
      _badgeCounts[tabIndex] = count;
    } else {
      _badgeCounts.remove(tabIndex);
    }
    update();
  }
  
  // 清除角标
  void clearBadge(int tabIndex) {
    _badgeCounts.remove(tabIndex);
    update();
  }
  
  // 清除所有角标
  void clearAllBadges() {
    _badgeCounts.clear();
    update();
  }
}